<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/9
 * Time: 15:53
 */

namespace App\Http\Middleware;


use App\Http\Model\AdminSessionModel;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class ApiAuth
{
    /**
     * 处理api权限问题.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $adminId = $this->tokenValidate($request);
        if (!$adminId) {
            return Response::create(['code' => 100001, 'msg' => '身份信息已过时，请重新登录'], 403);
        }else{
            $request->session()->put('adminId',$adminId);
        }

        return $next($request);
    }

    /**
     * 对接口进行token验证
     *
     * @param $request
     * @return bool
     */
    private function tokenValidate($request)
    {
        $tokenRequest = $request->input(config('yucheng.token'), '');
        //验证token是否存在
        $adminSession = AdminSessionModel::get($tokenRequest);
        if (empty($adminSession)){
            return false;
        }
        //验证token是否超时
        $curTimestamp = intval(time());
        $sessionTimestamp = intval(strtotime($adminSession['tokenTime']));
        if (($curTimestamp-$sessionTimestamp) >= config('yucheng.tokenExist')){
            return false;
        }
        AdminSessionModel::put($tokenRequest,$adminSession['adminId']);
        return $adminSession['adminId'];
    }
}